import CryptoJS from "crypto-js";
// 授权前告知用户权限意图
export async function showAuthTipModal(authorize) {
  // #ifdef H5
  if (1 === 1) {
    return {
      bool: true,
    };
  }
  // #endif
  // ios端在manifest.json配置权限使用说明，以下权限判断仅在安卓端可用
  let isIos = await checkIsIos();
  if (isIos)
    return {
      bool: isIos,
    };
  let compat = plus.android.importClass("androidx.core.content.ContextCompat");
  let context = plus.android.runtimeMainActivity();
  let result = compat.checkSelfPermission(context, authorize);
  console.log(result);
  if (result === 0)
    return {
      bool: true,
      result: true,
    };
  // // 如果已经授权直接返回
  return new Promise((resolve) => {
    uni.showModal({
      title:
        Vue.prototype.$store.state.scsPublic.appAuthPermission[authorize].title,
      content:
        Vue.prototype.$store.state.scsPublic.appAuthPermission[authorize]
          .describe,
      success: (res) => {
        resolve({
          bool: !!res.confirm,
          result: false,
        });
        // 如果没有权限，弹出提示框，bool为弹出框的确认、取消布尔值，result为没有开启对应权限
      },
    });
  });
}
// 授权失败，提示用户手动开启

export async function showManualAuth(authorize) {
  let isIos = await checkIsIos();
  if (isIos)
    return {
      bool: isIos,
    };
  uni.showModal({
    title: "提示",
    content:
      Vue.prototype.$store.state.scsPublic.appAuthPermission[authorize]
        .noPermissionDes,
    confirmText: "去设置",
    success: (res) => {
      if (res.confirm) {
        uni.openAppAuthorizeSetting({
          success(res) {
            console.log(res);
          },
        });
      }
      if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
}
// 语音转文字
export async function voiceToText(params) {
  return "voiceToText";
}

export function checkIsIos(params) {
  // 查询是否是ios
  return new Promise((resolve) => {
    uni.getSystemInfo({
      success: function (res) {
        resolve(res.platform === "ios");
      },
    });
  });
}

/**
 * 获取websocket url
 * 该接口需要后端提供，这里为了方便前端处理
 */
function getWebSocketUrl(API_KEY, API_SECRET) {
  // 请求地址根据语种不同变化
  var url = "wss://iat-api.xfyun.cn/v2/iat";
  var host = "iat-api.xfyun.cn";
  var apiKey = API_KEY;
  var apiSecret = API_SECRET;
  var date = new Date().toGMTString();
  var algorithm = "hmac-sha256";
  var headers = "host date request-line";
  var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/iat HTTP/1.1`;
  var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
  var signature = CryptoJS.enc.Base64.stringify(signatureSha);
  var authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
  var authorization = btoa(authorizationOrigin);
  url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
  return url;
}

export function useWebSocket() {
  const APPID = "39012a77";
  const APISecret = "ZjE2YzYyMWRmNGZmMTkyY2E5NWQyNzI4";
  const APIKey = "17cc7c32d8ba5b690a60d3001cf588f4";
  const socketTask = uni.connectSocket({
    url: getWebSocketUrl(APIKey, APISecret),
    success: (e) => {
      console.log("🚀 ~ useWebSocket ~ success:", e);
    },
  });
  console.log("🚀 ~ useWebSocket ~ socketTask:", socketTask);
  return socketTask;
}
